package com.guoqing.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * @author zhangguoqing
 * @date 2020/9/7
 * Description: TODO
 *
 *
 * <plugin>
 * <groupId>org.apache.maven.plugins</groupId>
 * <version>2.6</version>
 * <artifactId>maven-resources-plugin</artifactId>
 * <configuration>
 * <encoding>UTF-8</encoding>
 * <nonFilteredFileExtensions>
 * <nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
 * </nonFilteredFileExtensions>
 * </configuration>
 * </plugin>
 */
@Slf4j
public class DownloadUtil {

    /**
     * @param templateName 模板名称
     * @param response     response
     */
    public static void downloadTemplate(String templateName, HttpServletResponse response) {
        ClassPathResource resource = new ClassPathResource("templates" + File.separator + templateName);
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            response.reset();
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(templateName, "utf-8"));
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            inputStream = resource.getInputStream();
            outputStream = response.getOutputStream();

            byte[] b = new byte[1024];
            int a = 0;
            while ((a = inputStream.read(b)) != -1) {
                outputStream.write(b, 0, a);
            }
            outputStream.flush();
        } catch (Exception ex) {
            log.error("[DownloadUtil downloadTemplate] Error: templateName:{}, {}", templateName, ex);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("[DownloadUtil downloadTemplate] Error: templateName:{}, {}", templateName, e);
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    log.error("[DownloadUtil downloadTemplate] Error: templateName:{}, {}", templateName, e);
                }
            }


        }
    }
}
